import type { PayInfo, PayOption } from '../types'

import { getPayInfo, getCardPayInfo, getCodeOpenIdInfo } from '../apis/index'

import { PayMode } from '../enums'

import { getWeChartAppOpenId, setWeChartAppOpenId } from '../utils/cookies'

import { os } from '../utils/index'
/**
 * @description 支付相关
 */
export const usePayEffect = (options: PayOption) => {
  const route = useRoute()
  const { orderSns, orderSn, lesseeId, appId, redirectUri, code, wxMiniOpenId } =
    route.query as Record<string, string | any>

  /**
   * @description 存储微信小程序的openID  【wxMiniOpenId】 ?? 这里是根据老项目逻辑来写 这里的这wxMiniOpenId不可以放在usePayEffect中处理吗？待验证
   */
  if (wxMiniOpenId) setWeChartAppOpenId(wxMiniOpenId)

  // 获取微信小程序openId
  const CookiesWXOpenId = getWeChartAppOpenId()

  const disabled = ref(false)

  // 公众号支付
  const wxJsApiPay = (data: any) => {
    /* eslint-disable */
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      {
        appId: data.appId, // 公众号名称，由商户传入
        timeStamp: data.timestamp, // 时间戳，自1970年以来的秒数
        nonceStr: data.nonceStr, // 随机串
        package: data.packageStr,
        signType: 'RSA',
        paySign: data.sign // 微信签名
      },
      function (res) {
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          // 使用以上方式判断前端返回,微信团队郑重提示：
          // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        } else {
          disabled.value = false
        }
      }
    )
  }

  // 小程序支付
  const wxMiNiProgramPay = (data: any) => {
    const pay_info = {
      timeStamp: data?.timestamp || '',
      nonceStr: data?.nonceStr || '',
      package: data?.packageStr || '',
      signType: 'RSA',
      paySign: data?.sign || ''
    }
    wx.miniProgram.navigateTo({
      url: `/pages/pay/index?pay_info=${encodeURIComponent(JSON.stringify(pay_info))}`,
      success: function () {},
      fail: function () {},
      complete: function () {
        disabled.value = false
      }
    })
  }

  /**
   *拉起支付
   */
  const handlePay = async () => {
    disabled.value = true

    let u = CookiesWXOpenId === undefined || CookiesWXOpenId === 'undefined'

    if (code && u) {
      // 获取小程序appID

      try {
        const { data } = await getCodeOpenIdInfo({
          code
        })

        setWeChartAppOpenId(data.openId)
      } catch (error) {
        disabled.value = false
        return
      }
    }

    const params: PayOption = {
      orderSn,
      orderSource: options.orderSource,
      orderSns: options.excludeZeroOrder.value || undefined,
      settleMode: options.settleMode.value,
      returnUrl: redirectUri
    }

    if ([PayMode.WX_MINI, PayMode.WX_JSAPI].includes(options.settleMode.value)) {
      // 小程序 | 公众号
      params.openId = CookiesWXOpenId
    }

    // 兼容购物车
    const pay = orderSn ? getPayInfo : getCardPayInfo

    try {
      const { data } = await pay(params)

      // 如果是pc微信支付则返回信息打开弹窗
      if (data.settleMode === PayMode.WX_NATIVE) {
        disabled.value = false
        return data
      }

      // 图书在app内打开
      if (os?.isBookInApp) {
        if (data && data.settleMode === PayMode.WX_H5) {
          const params = JSON.stringify(unref(data))
          if (os?.isAndroid) {
            window.android?.goToWxPay(params)
          } else if (os?.isPhone || os?.isTablet) {
            window.webkit?.messageHandlers.goToWxPay.postMessage(params)
          }
          disabled.value = false
          return
        }
        if (data && data.settleMode === PayMode.ALI_MOBILE) {
          const params = JSON.stringify({ payInfo: data.payInfo })
          if (os?.isAndroid) {
            window.android?.goToAliPay(params)
          } else if (os?.isPhone || os?.isTablet) {
            window.webkit?.messageHandlers.goToAliPay.postMessage(params)
          }
          return
        }
      }

      // 微信jsapi支付
      if (data && data.settleMode === PayMode.WX_JSAPI) {
        wxJsApiPay(data)
        return
      }
      // 小程序支付
      if (data && data.settleMode === PayMode.WX_MINI) {
        wxMiNiProgramPay(data)
        return
      }

      paySuccess(data)
    } catch (error) {
      disabled.value = false
    }
  }

  /**
   * @description 支付支付成功直接跳转
   */
  const paySuccess = (result: PayInfo) => {
    const sn = result.orderSn || orderSn
    const sns = result.orderSns || orderSns
    const orderKey = sns ? `orderSns=${encodeURIComponent(JSON.stringify(sns))}` : `orderSn=${sn}`
    disabled.value = false
    // 如果是免费跳转支付成功页面
    if ([PayMode.WX_H5, PayMode.WX_MINI].includes(result.settleMode)) {
      const pathUrl = `${location.origin}/?${orderKey}&lesseeId=${lesseeId}&appId=${appId}&redirectUri=${redirectUri}`
      window.location.replace(`${result.payInfo}&redirect_url=${encodeURIComponent(pathUrl)}`)
    } else {
      window.location.replace(result.payInfo)
    }
  }

  return {
    handlePay
  }
}
